package cn.iocoder.yudao.module.system.controller.admin.gugu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ProvinceScoreCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ProvinceScorePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ProvinceScoreRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.ProvinceScoreUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.gugu.ProvinceScoreConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.ProvinceScoreDO;
import cn.iocoder.yudao.module.system.service.gugu.ProvinceScoreService;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


/**
 * 历年高考省录取分数线数据 Controller
 */
@Tag(name = "管理后台 - 历年高考省录取分数线数据")
@RestController
@RequestMapping("/system/province-score")
@Validated
@Slf4j
public class ProvinceScoreController {

    @Resource
    private ProvinceScoreService provinceScoreService;

    @PostMapping("/create")
    @Operation(summary = "创建历年高考省录取分数线数据")
    @PreAuthorize("@ss.hasPermission('system:province-score:create')")
    public CommonResult<Long> createProvinceScore(@Valid @RequestBody ProvinceScoreCreateReqVO createReqVO) {
        return success(provinceScoreService.createProvinceScore(ProvinceScoreConvert.INSTANCE.convert(createReqVO)));
    }

    @PutMapping("/update")
    @Operation(summary = "更新历年高考省录取分数线数据")
    @PreAuthorize("@ss.hasPermission('system:province-score:update')")
    public CommonResult<Boolean> updateProvinceScore(@Valid @RequestBody ProvinceScoreUpdateReqVO updateReqVO) {
        provinceScoreService.updateProvinceScore(ProvinceScoreConvert.INSTANCE.convert(updateReqVO));
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除历年高考省录取分数线数据")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:province-score:delete')")
    public CommonResult<Boolean> deleteProvinceScore(@RequestParam("id") Long id) {
        provinceScoreService.deleteProvinceScore(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得历年高考省录取分数线数据")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:province-score:query')")
    public CommonResult<ProvinceScoreRespVO> getProvinceScore(@RequestParam("id") Long id) {
        ProvinceScoreDO provinceScore = provinceScoreService.getProvinceScore(id);
        return success(ProvinceScoreConvert.INSTANCE.convert(provinceScore));
    }

    @GetMapping("/page")
    @Operation(summary = "获得历年高考省录取分数线数据分页")
    @PreAuthorize("@ss.hasPermission('system:province-score:query')")
    public CommonResult<PageResult<ProvinceScoreRespVO>> getProvinceScorePage(@Valid ProvinceScorePageReqVO pageReqVO) {
        PageResult<ProvinceScoreDO> pageResult = provinceScoreService.getProvinceScorePage(pageReqVO);
        return success(ProvinceScoreConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出历年高考省录取分数线数据 Excel")
    @PreAuthorize("@ss.hasPermission('system:province-score:export')")
    public void exportProvinceScoreExcel(@Valid ProvinceScorePageReqVO pageReqVO,
                                         HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProvinceScoreDO> list = provinceScoreService.getProvinceScorePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "历年高考省录取分数线数据.xls", "数据", ProvinceScoreRespVO.class,
                ProvinceScoreConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/fetch")
    @Operation(summary = "获取历年高考省录取分数线数据")
    public CommonResult<Map<String, Object>> fetchProvinceScore(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "录取省份搜索关键字，如江苏。为空返回所有数据") @RequestParam(value = "keyword", required = false) String keyword,
            @Parameter(description = "录取数据的年份，2014 - 2024") @RequestParam(value = "year", required = false) Integer year,
            @Parameter(description = "录取学科分类筛选，综合、文科理科等") @RequestParam(value = "category", required = false) String category) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateProvinceScoreApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            // 调用服务获取并保存数据
            Map<String, Object> result = provinceScoreService.fetchAndSaveProvinceScore(appkey, keyword, year, category);
            return success(result);
        } catch (Exception e) {
            log.error("获取历年高考省录取分数线数据失败", e);
            return CommonResult.error(500, "获取数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @Operation(summary = "查询历年高考省录取分数线数据列表")
    public CommonResult<List<ProvinceScoreRespVO>> getProvinceScoreList(
            @Parameter(description = "录取省份", example = "江苏") @RequestParam(value = "province", required = false) String province,
            @Parameter(description = "录取年份，2014年 - 2024年", example = "2024") @RequestParam(value = "year", required = false) Integer year,
            @Parameter(description = "录取学科分类，综合、文科理科等", example = "物理类") @RequestParam(value = "category", required = false) String category) {

        // 从数据库获取数据
        List<ProvinceScoreDO> provinceScoreList = provinceScoreService.getProvinceScoreList(province, year, category);

        // 转换为VO对象
        return success(ProvinceScoreConvert.INSTANCE.convertList(provinceScoreList));
    }

    @DeleteMapping("/delete-by-year")
    @Operation(summary = "根据年份删除历年高考省录取分数线数据")
    @Parameter(name = "year", description = "年份", required = true, example = "2024")
    @PreAuthorize("@ss.hasPermission('system:province-score:delete')")
    public CommonResult<Integer> deleteProvinceScoreByYear(@RequestParam("year") Integer year) {
        int deletedCount = provinceScoreService.deleteProvinceScoreByYear(year);
        return success(deletedCount);
    }
}
